<?php
require_once 'file.func.php';
class attachment
{
    public $db;
    public $table;
    public $attachments;
    public $field;
    public $imageexts = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
    public $uploadedfiles = array();
    public $downloadedfiles = array();
    public $error;
    public $siteid = MASTER_ID;

    function attachment()
    {
        global $db;
        $this->db = &$db;
        $this->table = DB_PRE.'attachment';
    }

    function upload($field, $alowexts = UPLOAD_ALLOWEXT, $maxsize = 0)
    {
        $target_siteid = $this->siteid;

        if(!isset($_FILES[$field])) return false;
        $this->field = $field;
        $this->relpath = UPLOAD_ROOT.date('Y/md/'); //相对跟目录的地址
        $this->savepath = site_root($target_siteid, 1) . $this->relpath;
        
        $this->alowexts = $alowexts;
        $this->maxsize = $maxsize;

        $file = array('tmp_name' => $_FILES[$field]['tmp_name'], 'name' => $_FILES[$field]['name'], 'type' => $_FILES[$field]['type'], 'size' => $_FILES[$field]['size'], 'error' => $_FILES[$field]['error']);
        if(!dir_create($this->savepath))
        {
            $this->error = '8';
            $this->log($this->error());
            return false;
        }
        if(!is_dir($this->savepath))
        {
            $this->error = '8';
            $this->log($this->error());
            return false;
        }
        @chmod($this->savepath, 0777);
        if(!is_writeable($this->savepath))
        {
            $this->error = '9';
            $this->log($this->error());
            return false;
        }

        $fileext = fileext($file['name']);
        if(!preg_match("/^(".$this->alowexts.")$/", $fileext))
        {
            $this->error = '10';
            $this->log($this->error());
            return false;
        }
        if($this->maxsize && $file['size'] > $this->maxsize)
        {
            $this->error = '11';
            $this->log($this->error());
            return false;
        }
        if(!$this->isuploadedfile($file['tmp_name']))
        {
            $this->error = '12';
            $this->log($this->error());
            return false;
        }
        $filename = $this->getname($fileext);
        $savefile = $this->savepath.$filename;
        $savefile = preg_replace("/(php|phtml|php3|php4|jsp|exe|dll|asp|cer|asa|shtml|shtm|aspx|asax|cgi|fcgi|pl)(\.|$)/i", "_\\1\\2", $savefile);
        $filepath = $this->relpath.$filename;
        if(move_uploaded_file($file['tmp_name'], $savefile))
        {
            @chmod($savefile, 0644);
            $uploadedfile = array('filename'=>$file['name'],'siteid'=>$target_siteid, 'filepath'=>$filepath, 'filetype'=>$file['type'], 'filesize'=>$file['size'], 'fileext'=>$fileext);
            $aid = $this->add($uploadedfile);
            if(empty($aid))
            {
                $this->log("无法存入数据库");
                return false;
            }
        }
        else
        {
            $this->error = '5';
            $this->log($this->error());
            return false;
        }
        return $aid;
    }

    function add($uploadedfile)
    {
        $uploadedfile['uploadtime'] = TIME;
        $uploadedfile['uploadip'] = IP;
        $uploadedfile['isimage'] = in_array($uploadedfile['fileext'], $this->imageexts) ? 1 : 0;
        $res = $this->db->insert($this->table, $uploadedfile);
        if($res !== false)
        {
            $id = $this->db->uuid();
            $uploadedfile['aid'] = $id;
            $this->uploadedfiles[] = $uploadedfile;
            $this->attachments[$this->field][$id] = $uploadedfile['filepath'];
            return $id;
        }
        return false;
    }

    function get_one($id)
    {
        return $this->db->get_one($this->table, $id);
    }

    function delete($id)
    {
        $file = $this->get_one($id);
        $result = $this->db->fake_delete($this->table, array('id'=>$id));
        if($result)
        {
            $filepath = site_root($file['siteid'],1).$file['filepath'];
            if(file_exists($filepath))
            {
                unlink($filepath);
            }
        }
        else
        {
            $this->log("未找到要删除的数据");
            return false;
        }
        return true;
    }

    function download($id)
    {
        set_time_limit(3600);
        $file = $this->get_one($id);
        if(empty($file))
        {
            $this->error = 14; //文件不存在
            $this->log($this->error());
            return false;
        }
        $filepath = UPLOAD_ROOT.$file['filepath'];
        if(!file_exists($filepath))
        {
            $this->error = 14; //文件不存在
            $this->log($this->error());
            return false;
        }
        $filesize = filesize($filepath);
        $filename = urlencode($file['filename']);
        header('Cache-Control: pre-check=0, post-check=0, max-age=0');
        header("Content-type: application/octet-stream");
        header("Accept-Ranges: bytes");
        header("Accept-Length: ".$filesize);
        header("Content-Length: " .$filesize);  //这个返回文件大小
        header("Content-Disposition: attachment; filename=".$filename);

        $fp = fopen($filepath,"r"); // 打开文件
        while(!feof($fp))
        {
            echo fread($fp,8192);
        }
        fclose($fp);
        exit;
    }

    function getname($fileext)
    {
        return date('Ymdhis').rand(100, 999).'.'.$fileext;
    }

    function list_info()
    {
        return $this->db->query("select * from $this->table where status=".STATUS_NORMAL);
    }

    function size($filesize)
    {
        if($filesize >= 1073741824)
        {
            $filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
        }
        elseif($filesize >= 1048576)
        {
            $filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
        }
        elseif($filesize >= 1024)
        {
            $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
        }
        else
        {
            $filesize = $filesize . ' Bytes';
        }
        return $filesize;
    }

    function isuploadedfile($file)
    {
        return is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file));
    }

    function error()
    {
        $ERROR = array(
            0 => '文件上传成功',
            1 => '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值',
            2 => '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值',
            3 => '文件只有部分被上传',
            4 => '没有文件被上传',
            5 => '文件上传失败',
            6 => '找不到临时文件夹。',
            7 => '文件写入临时文件夹失败',
            8 => '附件目录创建不成功',
            9 => '附件目录没有写入权限',
            10 => '不允许上传该类型文件',
            11 => '文件超过了管理员限定的大小',
            12 => '非法上传文件',
            13 => '24小时内上传附件个数超出了系统限制',
            14 => '文件不存在',
        );
        return $this->error ? $ERROR[$this->error] : '';
    }

    function log($msg)
    {
        global $log;
		$log->write_error_log($msg);
    }
}
?>